/*
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.lvyh.lightframe.transaction.core.service.impl;

import com.lvyh.lightframe.transaction.common.context.TransactionContext;
import com.lvyh.lightframe.transaction.common.enums.TransactionRole;
import com.lvyh.lightframe.transaction.common.thread.TransactionThreadLocal;
import com.lvyh.lightframe.transaction.core.coordinator.RemoteTransactionCoordinator;
import com.lvyh.lightframe.transaction.core.factory.TransactionCoordinatorFactory;
import com.lvyh.lightframe.transaction.core.service.RemoteCoordinatorService;
import org.springframework.stereotype.Service;

import java.util.Objects;

@Service
public class RemoteCoordinatorServiceImpl implements RemoteCoordinatorService {
    @Override
    public RemoteTransactionCoordinator getHandlerStrategy(TransactionContext remoteTransactionContext) {
        //If the transaction context object passed in remotely is null, the current transaction may be the transaction initiator or a local transaction
        if (Objects.isNull(remoteTransactionContext)) {

            //Gets the transaction context object of the current thread. If it is not empty and the role is local, the current transaction is a local transaction
            //In the case of MQ calls, the role of the transaction context object is set to local
            TransactionContext localTransactionContext = TransactionThreadLocal.CONTEXT_THREADLOCAL.get();

            if (localTransactionContext != null && Objects.equals(localTransactionContext.getRole(), TransactionRole.LOCAL.getCode())) {
                return TransactionCoordinatorFactory.getTransactionCoordinator(TransactionRole.LOCAL);
            } else {
                //Transaction Originator
                return TransactionCoordinatorFactory.getTransactionCoordinator(TransactionRole.START);
            }
        } else {
            //Transaction participant
            return TransactionCoordinatorFactory.getTransactionCoordinator(TransactionRole.ACTOR);
        }

    }
}
